<template>
  <div class="body">
    <div class="title">试题录入</div>
    <hr style="border: 0; border-top: #ccc 0.5px solid" />
    <el-form ref="form" :model="form" :rules="rules" label-width="80px">
      <el-form-item label="学科:" prop="subjectID">
        <el-select v-model="form.subjectID" placeholder="请选择">
          <el-option
            v-for="item in subjectList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="目录:" prop="catalogID">
        <el-select v-model="form.catalogID" placeholder="请选择">
          <el-option
            v-for="item in catalogList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="企业:" prop="enterpriseID">
        <el-select v-model="form.enterpriseID" placeholder="请选择">
          <el-option
            v-for="item in companysList"
            :key="item.id"
            :label="item.company"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="城市" class="city" prop="city">
        <el-select v-model="form.province" placeholder="请选择">
          <el-option
            v-for="(item, index) in provinces"
            :key="index"
            :label="item"
            :value="item"
          ></el-option
        ></el-select>
        <el-select v-model="form.city" placeholder="请选择">
          <el-option
            v-for="(item, index) in citys"
            :key="index"
            :label="item"
            :value="item"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="方向:" prop="direction">
        <el-select v-model="form.direction" placeholder="请选择">
          <el-option
            v-for="item in direction"
            :key="item"
            :label="item"
            :value="item"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="题型:" prop="questionType">
        <el-radio-group v-model="form.questionType">
          <el-radio
            v-for="item in questionType"
            :key="item.value"
            :label="item.value + ''"
            >{{ item.label }}</el-radio
          >
        </el-radio-group>
      </el-form-item>
      <el-form-item label="难度:" prop="difficulty">
        <el-radio-group v-model="form.difficulty">
          <el-radio
            v-for="item in difficulty"
            :key="item.value"
            :label="item.value + ''"
            >{{ item.label }}</el-radio
          >
        </el-radio-group>
      </el-form-item>
      <el-form-item label="题干:" prop="question" label-width="85px">
        <quillEditor v-model="form.question" :options="editorOption" />
      </el-form-item>
      <el-form-item label="选项:" v-if="+this.form.questionType !== 3" label-width="85px">
        <el-row>
          <el-checkbox-group
            v-model="isRight"
            v-if="+this.form.questionType === 2"
          >
            <div
              class="option_item"
              v-for="(item, index) in form.options"
              :key="item.code"
            >
              <el-checkbox :label="item.code" :value="item.code"></el-checkbox>

              <el-input v-model="item.title" style="width: 250px" />
              <el-upload
                class="avatar-uploader"
                action="https://jsonplaceholder.typicode.com/posts"
                :show-file-list="false"
                :on-success="
                  (res, file) => {
                    handleAvatarSuccess(res, file, index);
                  }
                "
                :before-upload="beforeAvatarUpload"
              >
                <div v-if="item.img" class="avatar">
                  <img :src="item.img" />
                </div>
                <div v-else class="avatar-uploader-icon">上传图片</div>
              </el-upload>
            </div>
          </el-checkbox-group>
          <el-radio-group v-model="isRight" v-else>
            <div
              class="option_item"
              v-for="(item, index) in form.options"
              :key="item.code"
            >
              <el-radio :label="item.code"></el-radio>

              <el-input v-model="item.title" style="width: 250px" />
              <el-upload
                class="avatar-uploader"
                action="https://jsonplaceholder.typicode.com/posts"
                :show-file-list="false"
                :on-success="
                  (res, file) => {
                    handleAvatarSuccess(res, file, index);
                  }
                "
                :before-upload="beforeAvatarUpload"
              >
                <div v-if="item.img" class="avatar">
                  <img :src="item.img" />
                </div>
                <div v-else class="avatar-uploader-icon">上传图片</div>
              </el-upload>
            </div>
          </el-radio-group>
        </el-row>
        <el-row>
          <el-button
            @click="addRadio"
            type="danger"
            size="small"
            :disabled="+this.form.questionType !== 2"
            >+增加选项与答案</el-button
          >
        </el-row>
      </el-form-item>
      <el-form-item label="解析视频:">
        <el-input v-model="form.videoURL" />
      </el-form-item>
      <el-form-item label="答案解析:" prop="answer" label-width="85px">
        <quillEditor v-model="form.answer" :options="editorOption" />
      </el-form-item>
      <el-form-item label="题目备注:">
        <el-input v-model="form.remarks" type="textarea" />
      </el-form-item>
      <el-form-item label="试题标签:">
        <el-select
          v-model="form.tags"
          placeholder="请选择"
          multiple
          filterable
          allow-create
        >
          <el-option
            v-for="(item, index) in tagsList"
            :key="index"
            :label="item.label"
            :value="item.label"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">确认提交</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { quillEditor } from 'vue-quill-editor'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'

import { simple as getSubjectList } from '@/api/hmmm/subjects.js'
import { simple as getCatalogList } from '@/api/hmmm/directorys.js'
import { simple as getTagsList } from '@/api/hmmm/tags.js'
import { list as getCompanysList } from '@/api/hmmm/companys.js'
import { questionType, difficulty, direction } from '@/api/hmmm/constants.js'
import { provinces, citys } from '@/api/hmmm/citys.js'
import { add, detail, update } from '@/api/hmmm/questions.js'
export default {
  components: {
    quillEditor
  },
  data () {
    return {
      editorOption: {
        placeholder: '',
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'], // 加粗，斜体，下划线，删除线
            [{ list: 'ordered' }, { list: 'bullet' }], // 列表
            ['blockquote'],
            ['code-block', 'image', 'link'] // 上传图片、上传视频
          ]
        }
      },
      direction,
      questionType,
      difficulty,
      form: {
        subjectID: null,
        catalogID: null,
        enterpriseID: null,
        province: null,
        city: null,
        direction: null,
        questionType: '1',
        difficulty: '1',
        question: '',
        options: [
          { isRight: false, code: 'A', title: '', img: null },
          { isRight: false, code: 'B', title: '', img: null },
          { isRight: false, code: 'C', title: '', img: null },
          { isRight: false, code: 'D', title: '', img: null }
        ],
        videoURL: null,
        answer: null,
        remarks: null,
        tags: null
      },
      rules: {
        subjectID: { required: true, message: '请选择学科' },
        catalogID: { required: true, message: '请选择目录' },
        enterpriseID: { required: true, message: '请选择企业' },
        city: { required: true, message: '请选择地区' },
        direction: { required: true, message: '请选择方向' },
        questionType: { required: true, message: '请选择题型' },
        difficulty: { required: true, message: '请选择难度' },
        question: { required: true, message: '请输入题干' },
        answer: { required: true, message: '请输入解析' }
      },
      imageUrl: '',
      subjectList: [],
      catalogList: [],
      companysList: [],
      tagsList: null,
      isRight: ''
    }
  },
  async created () {
    this.getSubjectList()
    this.getCompanysList()
    if (this.$route.query.id) {
      const { data } = await detail({ id: this.$route.query.id })
      const options = [...data.options]
      this.form = { ...data }
      await this.$nextTick()
      this.form.city = data.city
      this.form.options = options
      this.form.tags = data.tags.split(',')
      if (+data.questionType === 1) {
        this.isRight = options.find(i => i.isRight).code
      } else if (+data.questionType === 2) {
        console.log(options.filter(i => !!i.isRight))
        this.isRight = options.filter(i => !!i.isRight).map(j => j.code)
      }
    }
  },
  computed: {
    provinces () {
      return provinces()
    },
    citys () {
      return citys(this.form.province)
    }
  },
  watch: {
    'form.subjectID' (newVal) {
      this.getCatalogList(newVal)
      this.getTagsList(newVal)
      this.form.catalogID = null
      this.form.tags = null
    },
    'form.province' () {
      this.form.city = null
    },
    'form.questionType' (newVal) {
      if (newVal !== '3') {
        this.form.options = [
          { isRight: false, code: 'A', title: '', img: null },
          { isRight: false, code: 'B', title: '', img: null },
          { isRight: false, code: 'C', title: '', img: null },
          { isRight: false, code: 'D', title: '', img: null }
        ]
        this.isRight = newVal === 1 ? '' : []
      } else {
        this.form.options = null
        this.isRight = null
      }
    }
  },
  methods: {
    onSubmit () {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          if (+this.form.questionType === 1) {
            this.form.options.forEach((i) => {
              i.isRight = i.code === this.isRight
            })
          } else if (+this.form.questionType === 2) {
            this.form.options.forEach((i) => {
              i.isRight = this.isRight.indexOf(i.code) !== -1
            })
          }
          this.form.tags = this.form.tags.join(',')
          if (this.$route.query.id) {
            await update({ ...this.form, id: +this.$route.query.id })
            this.$message.success('修改成功')
          } else {
            await add(this.form)
            this.$message.success('添加成功')
          }
          this.$router.push('/questions/list')
        }
      })
    },
    async getSubjectList () {
      const { data } = await getSubjectList()
      this.subjectList = data
    },
    async getCatalogList (subjectID) {
      const { data } = await getCatalogList({ subjectID })
      this.catalogList = data
    },
    async getTagsList (subjectID) {
      const { data } = await getTagsList({ subjectID })
      this.tagsList = data
    },
    async getCompanysList () {
      const { data } = await getCompanysList({ pagesize: 1000 })
      this.companysList = data.items
    },
    handleAvatarSuccess (res, file, i) {
      this.form.options[i].img = URL.createObjectURL(file.raw)
    },
    beforeAvatarUpload (file) {
      const isJPG = file.type === 'image/jpeg'
      const isPNG = file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG && !isPNG) {
        this.$message.error('上传头像图片只能是 JPG 或者 png 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return (isJPG || isPNG) && isLt2M
    },
    addRadio () {
      this.form.options.push({
        isRight: false,
        code: String.fromCharCode(65 + this.form.options?.length),
        title: '',
        img: null
      })
    }
  }
}
</script>

<style scoped lang="scss">
.body {
  box-sizing: border-box;
  padding: 20px;
  max-width: 100%;
  margin: 10px 20px;
  background-color: #fff;
  color: #303133;
  .title {
    margin-bottom: 16px;
  }
  .el-form {
    .el-form-item {
      .el-select,
      .el-input,
      .el-textarea {
        width: 400px;
      }
      &.city {
        .el-select {
          width: 198px;
          margin-right: 4px;
        }
      }
    }
  }
}
.quill-editor {
  ::v-deep .ql-editor {
    min-height: 200px;
  }
}
.avatar-uploader {
  display: inline-block;
  margin-left: 5px;
  .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }
  .avatar-uploader-icon {
    font-size: 14px;
    color: #333;
    width: 100px;
    height: 60px;
    line-height: 60px;
    border: 1px dashed #ccc;
    border-radius: 15px;
    text-align: center;
  }
  .avatar {
    float: left;
    width: 100px;
    height: 60px;
    border: 1px dashed #ccc;
    border-radius: 15px;
    line-height: 60px;
    text-align: center;
    img {
      width: 100%;
      height: 100%;
      border-radius: 15px;
    }
  }
}
.el-form-item {
  ::v-deep .el-form-item__label {
    width: 85px !important;
  }
  .option_item {
    display: flex;
    align-items: center;
    height: 60px;
    margin: 20px 0;
    label {
      margin-right: 10px !important;
    }
  }
}
</style>
